
// import './magnific-popup.css'; //删除对话框必要的css
import '../../css/plugins/bootstrap-table/bootstrap-table.css';

// require ('./jquery.magnific-popup.min.js'); //删除对话框必要的js

require('../plugins/bootstrap-table/bootstrap-table.js');
require('../plugins/bootstrap-table/bootstrap-table-zh-CN.min.js');

require('../plugins/jqpaginator/jqPaginator.min.js'); //分页js

require('../plugins/layer/layer.js') //弹出层js
var configs;

// jQuery.fn.bootstrapTable.defaults({
// 	undefinedText: '-',
// 	pagination: false,
// 	clickToSelect: false
// });
Date.prototype.format = function(format) {
/*
    * eg:format="YYYY-MM-dd hh:mm:ss";
  */
    var o = {
        "M+" :this.getMonth() + 1, // month
        "d+" :this.getDate(), // day
        "h+" :this.getHours(), // hour
        "m+" :this.getMinutes(), // minute
        "s+" :this.getSeconds(), // second
        "q+" :Math.floor((this.getMonth() + 3) / 3), // quarter
        "S" :this.getMilliseconds()
    // millisecond
    }
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "")
                .substr(4 - RegExp.$1.length));
    }

    for ( var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k]
                    : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
}

function dateFormatter(value, row) { //格式化时间戳
	return (new Date(parseInt(value) * 1000).format(configs.table.date_forma.formatter.toString()))
}
//判断是否是
function isArray (value) {
    if  (Object.prototype.toString.call(value) === '[object Array]') {
        return true
    }
    return false

}
let  resData;
function tableInit(base_config) {
	this.table = base_config.table;
	this.del_action = base_config.del_action;
	this.detail_action = base_config.detail_action;
	this.list = base_config.list;
	let $table = $(base_config.table.id);
	this.$table = $table;
	this.page = base_config.page;
	this.pageOption = base_config.pageOption;

	
	if(base_config.edit_action !== undefined) {
		this.edit_action = base_config.edit_action;
		this.edit_modal = base_config.edit_action.edit_modal;

		// console.log('有修改选项');
	}

	let _self = this;
	configs = base_config;

	

	let type = typeof base_config.list.type === 'undefined' ? 'POST' : base_config.list.type;
	let req_data = base_config.list.data || '';
	let operate = [];

	let creat_operate = function() {
		return operate.join('')
	}
	var operateEvents = {
		'click .remove-row': function (e, value, row, index) { //删除
		    _self.rowDelete(row);

		        // alert('editor, row: ' + JSON.stringify(row));
		},
	    'click .edit-row': function (e, value, row, index) {
	    	
	    	_self.rowEdit(row)
	        // table.rowDelete('../data/bootstrap-table-delect.json',row.id,"确定要删除这一行？",true)
	    },
	    'click .detail-row': function(e, value, row, index) {
	    	
	    	_self.lookDetail(row)
	    }
	}
	
	if(base_config.table.checkbox) { // 添加checkbox
		base_config.table.columns.unshift({checkbox: true})
	}
	if(typeof base_config.table.date_forma != 'undefined') { // 日期格式化
		let date_obj = base_config.table.date_forma;
		let columns = base_config.table.columns;
		let field = date_obj.field;
		columns.forEach(v => {
			if(v.field === field) {
				v.formatter = dateFormatter
			}

		})
	}

	if(typeof base_config.table.actions != 'undefined') { // 表格的操作
		operate = []
		let actions = base_config.table.actions;
		for(let j = 0,len=actions.length; j < len; j++) {
   			switch(actions[j]) {
   				case 'del':
   					operate.push('<button  class="btn btn-danger btn-xs remove-row" style="margin-right:5px;">删除</button>') 
   					break;
   				case 'edit': 
   					operate.push('<button  class="btn btn-primary btn-xs edit-row" style="margin-right:5px;">修改</button>')
   					break;
   				case 'detail':
   					operate.push('<button  class="btn btn-xs detail-row" style="margin-right:5px;">查看</button>') 
   					break;
   				// default operate = []	
   				// return 
   			}
		}

		let columns_length = base_config.table.columns.length;
		base_config.table.columns[columns_length-1].formatter = creat_operate;
		base_config.table.columns[columns_length-1].events = operateEvents
	}
	// console.log(base_config.table.columns)
	 // $table.bootstrapTable('destroy'); 
	var table = $table.bootstrapTable({
		ajax: function() {
			$.ajax({  
	            type: type,
	            url: base_config.list.url,   
	            dataType:"json",  
	            data:  req_data,  
	            success : function (res) {
	            	$(".fixed-table-loading").hide()
	            	console.log(res)
	            	
	            	if(res.status === 1) {
	            		
	            		_self.data = res.data;
	            		resData = res.data;
	            		console.log(_self.data)
	            		if(base_config.page && parseInt(res.data._total.count)) {
	            			$(_self.pageOption.id).show()
							let pageOption = base_config.pageOption;
							pageOption.total = parseInt(res.data._total.count);
							pageOption.current = parseInt(res.data._total.page);
							pageOption.size = parseInt(res.data._total.page_number)
							new Paginate(pageOption, configs.list, $table)
						}
						if(res.data.items.length > 0) {
							$table.bootstrapTable('load', res.data.items); 
						}else {
							$table.bootstrapTable('load', []); 
						}
						
	            		
	            	}	
	                

	            },  
	            error:function(){ 

	                alert("错误");  
	            }  
	        }); 
		},
		columns: base_config.table.columns,
		pagination: false, //分页
		toolbar: base_config.table.toolbar,

	}).on('check.bs.table', function(row) {
		let $delbtn_all = $(base_config.table.toolbar).find('#btn_delete')
		$delbtn_all.prop('disabled', false)
	}).on('uncheck.bs.table', function() {
		let ids = $.map($table.bootstrapTable('getSelections'), function (row) {
            return row.id
        });
        let $delbtn_all = $(base_config.table.toolbar).find('#btn_delete');
        if(ids.length === 0) {
        	$delbtn_all.prop('disabled', true)
        }
	}).on('check-all.bs.table', function(rows) {
		let $delbtn_all = $(base_config.table.toolbar).find('#btn_delete');
		let ids = $.map($table.bootstrapTable('getSelections'), function (row) {
            return row.id
        });
        if(ids.length === 0) {
        	$delbtn_all.prop('disabled', true)
        }else {
        	$delbtn_all.prop('disabled', false)
        }
		
	}).on('uncheck-all.bs.table', function(rows) {
		let $delbtn_all = $(base_config.table.toolbar).find('#btn_delete')
		$delbtn_all.prop('disabled', true)
	}).on('load-success.bs.table',function(data){
       console.log("load success");
    });
	$table.bootstrapTable('getData',function(useCurrentPage) {
		console.log(useCurrentPage)
	})
$table.bootstrapTable('getSelections'), function (row) {
        console.log(row.id)
    }
	
	// return new Promise(function(resolve, reject) {
 //        let url = option.url;
 //        console.log(typeof url === 'undefined')
	// 	let data = option.data || '';
	// 	let type = option.type || 'POST';
	// 	if(typeof url === 'undefined' || (url.length === 0 && typeof url != 'undefined')) {
	// 		return 
	// 	}else {
	// 		$.ajax({
	// 			url: url,
	// 			data: data,
	// 			type: type,
	// 			dataType: 'json',
	// 			success: function(res) {
	// 				console.log(res)
	// 				if(res.status === 1) {
	// 					resolve(res)
	// 				}
	// 			},
	// 			error: function(res) {
	// 				reject(res);
	// 			}
	// 		})
	// 	}
 //    });
 return this;
}

// let m = new tableInit()
tableInit.prototype.rowDelete = function(row) { //单选删除
	let _self = this;
	TableAction.initialize({
		table: _self.table.id,
		delbtn: '.remove-row'
	}).rowDelete(row,this.del_action)
}
tableInit.prototype.getEditColumns = function() {
	let array = [];

	return array
}
tableInit.prototype.delChecked = function(ele) { // 多选删除
	let $table = $(this.table.id);
	let ids = $.map($table.bootstrapTable('getSelections'), function (row) {
        return row.id
    });
    let del_obj = this.del_action;
    let postdata = del_obj.data;
    postdata[del_obj.post_key] = ids;
	$.ajax({
		url: del_obj.url,
	  	type: del_obj.type,
	  	dataType:'JSON',
	  	data: postdata,
	  	success: function(res) {
	  		if(res.status === 1) {
	  			if(res.msg === '删除成功') {
	  				$table.bootstrapTable('remove', {
				    	field: 'id',
				        values: ids
				    });
				    layer.msg('删除成功', {
			  			time: 1000
			  		})
			  		ele.prop('disabled', true)	
	  			}else {
	  				layer.msg('删除失败，请稍后重试', {
			  			time: 1000
			  		})
	  			}
	  		}
	  	},
	  	error: function(res) {
	  		layer.msg('删除失败，请稍后重试', {
	  			time: 1000
	  		})
	  	}
	})
    
}

tableInit.prototype.lookDetail = function(row) { //查看详情
	let detail_data = this.detail_action;
	let $modal = $(detail_data.detail_modal.id);
	let key = detail_data.postkey;
	let creat_ele = detail_data.detail_modal.info_ele;
	let columns = detail_data.detail_modal.detail_columns;

	columns.forEach(function(v) {
		$modal.find('.'+v.class).find(creat_ele).remove()	
	})
	$modal.modal('show')
	if(isArray(detail_data.postkey)) {

	}else {
		detail_data.postdata[key] = row[key];
	}
	$.ajax({
		url: detail_data.url,
		data: detail_data.postdata,
		type: detail_data.type,
		dataType: 'json',
		success: function(res) {
			if(res.status === 1) {

				for(let key in res.data) {
					if(isArray(res.data[key])) {
						let data_array = res.data[key];
						columns.forEach(function(v) {
							if(v.data_key === key) {
								for(let index=0;index < data_array.length; index++) {
									let $ele = $("<"+creat_ele+"></"+creat_ele+">");
									$ele.text(data_array[index])
									$modal.find('.'+v.class).append($ele)
								}
								
							}
						})
						
					}else {
						let $ele = $("<"+creat_ele+"></"+creat_ele+">");
						if($ele[0].nodeName === 'SPAN') {
							if(res.data[key].length === 0) {
								res.data[key] = '暂无';
							}
							$ele.text(res.data[key])
						}else if($ele[0].nodeName === 'INPUT') {
							$ele.val(res.data[key]).prop('readonly', true)
						}
						columns.forEach(function(v) {
							if(v.data_key === key) {
								$modal.find('.'+v.class).append($ele)
							}
						})						
						
					}

					
				}
			}
			
		}
	})
	
}

tableInit.prototype.searchFun = function(form) {
	let _self = this;
	let $form = $(form);
	let search_data = $form.serializeArray();
	$.each(search_data, function(i, field){
		console.log(field)
		if(field.value === "" || field.value === "请选择"){
			_self.list.data.params[field.name] = ''	 
		}else {
			_self.list.data.params[field.name] = field.value
		}		
    });
    $.ajax({  
        type: _self.list.type,
        url: _self.list.url,   
        dataType:"json",  
        data: _self.list.data,  
        success : function (res) {        	
        	if(res.status === 1) {
        		if(_self.page && parseInt(res.data._total.count)) {
        			$(_self.pageOption.id).show()
					let pageOption = _self.pageOption;
					pageOption.total = parseInt(res.data._total.count);
					pageOption.current = parseInt(res.data._total.page);
					pageOption.size = parseInt(res.data._total.page_number)
					new Paginate(pageOption, _self.list, _self.$table)
				}else {
					$(_self.pageOption.id).hide()
				}
				_self.$table.bootstrapTable('load', res.data.items); 
        		
        	}	
        },  
        error:function(){ 

            alert("错误");  
        }  
    }); 
}


tableInit.prototype.rowEdit = function(row) {
	let _self = this;
	let $modal =  $(this.edit_modal.id);
	$modal.modal('show')
	let $form = $modal.find(_self.edit_modal.formid);
	let key = this.edit_action.post_key;
	this.edit_action.data[key] = row[key];
	let form_ele = this.edit_modal.form_ele;

	$.ajax({
		url: _self.edit_action.url,
		type: _self.edit_action.type,
		dataType:"json",
		data: _self.edit_action.data,
		success: function(res) {
			if(res.status === 1) {
				form_ele.forEach(v => {
					if(v.type === 'input') {
						$form.find('input[name="'+v.name+'"]').val(res.data[v.field_key])
					}
					if(v.type === 'select') {
						$form.find('select[name="'+v.name+'"]').find('option').remove();
						let option =  $("<option></option>");
						option.val(res.data[v.field_key]).text(res.data[v.text]).appendTo($form.find('select[name="'+v.name+'"]'));
						// $form.find('select[name="'+v.name+'"]').val(res.data[v.field_key])
					}
				})
			}
			console.log(res)
		}
	})
	console.log(row)
}
tableInit.prototype.getData = function() {
	console.log(this.data)
	return this.data;
}


/*分页*/
function Paginate(option, req_list, table) {
	this.option = option;
	this.req_list = req_list;
	this.$table = table;
	this.init();
}
Paginate.prototype.init = function() {
	let _self = this;
	let set_defalut = {
		next: '<li class="next"><a href="javascript:;">Next</a></li>',
		prev: '<li class="prev"><a href="javascript:;">Previous</a></li>',
		page: '<li class="page"><a href="javascript:;">{{page}}</a></li>',
		totalCounts: this.option.total,
		visiblePages: this.option.visiblePages,
		currentPage: this.option.current,
		pageSize: this.option.size,
		onPageChange: function(num, type) {
			if(type === 'init') {
			}else {
				_self.pageChange(num)
			}
		}
	}
	$.jqPaginator(this.option.id, set_defalut);
	
}
Paginate.prototype.pageChange = function(num) {
	console.log(this.req_list)
	this.req_list.data.pages.page = num;
	let _self = this;
	$.ajax({
		type: this.req_list.type,
        url: this.req_list.url,   
        dataType: "json",  
        data: this.req_list.data,  
        success : function (res) {
        	console.log(res)
        	
        	if(res.status === 1) {
				_self.$table.bootstrapTable('load', res.data.items); 
        		
        	}	
            

        },  
        error:function(){ 

            alert("错误");  
        }  
	})
}







const TableAction = {
	options: {
		table: '',
		delbtn: '',
		// deldialog: {
		// 	wrapper: '',
		// 	cancelButton: '',
		// 	confirmButton: '',
		// },
	// 	editorbtn: ''
	},
	initialize: function(option) {

		this.options.table = option.table;
		this.options.delbtn = option.delbtn;
	// 	if(option.delbtn != false || this.options.delbtn != '') {
	// 		this.options.deldialog = option.deldialog;
	// 	}
	// 	this.options.editorbtn = option.editorbtn;
		this.setVars()
		return this;
	},
	setVars: function() {
		this.$table = $(this.options.table);
		this.$delbtn = $(this.options.delbtn);

	// 	this.dialog	= {};
	// 	this.dialog.$wrapper = $( this.options.deldialog.wrapper );
	// 	this.dialog.$cancel	= $( this.options.deldialog.cancelButton );
	// 	this.dialog.$confirm = $( this.options.deldialog.confirmButton );
	// 	this.$editbtn = $(this.options.editorbtn)
		return this;
	},
	rowDelete: function(rowdata,post_obj) {
		console.log(post_obj);
		this.$table.on('click', this.options.delbtn, function(e) {
			let obj = $.extend(true, {}, post_obj['data']);
			
			let key = post_obj.post_key;
			
			obj[key] = [];
			obj[key].push(rowdata[key]);
			post_obj['data'] = obj;
			let $row = $(this).closest( 'tr' );	
					
			layer.confirm('您确定要删除该条信息吗？', {
			  btn: ['确定', '取消'], //可以无限个按钮
			  skin: 'layui-layer-molv',
			  title: '提示信息'
			}, function(index, layero){
			  //按钮【按钮一】的回调
			  $.ajax({
			  	url: post_obj.url,
			  	type: post_obj.type,
			  	dataType:'JSON',
			  	data: post_obj['data'],
			  	success: function(res) {
			  		if(res.status === 1) {
			  			if(res.message === '删除成功') {
			  				$row.remove()
			  				layer.close(index)
			  			}else {
			  				layer.close(index)
					  		/* Act on the event */
					  		layer.msg('删除失败，请稍后重试', {
					  			time: 1000
					  		})
			  			}

			  		}

			  	},
			  	error: function() {
			  		layer.close(index)
			  		/* Act on the event */
			  		layer.msg('删除失败，请稍后重试', {
			  			time: 1000
			  		})
			  	}
			  })
			}, function(index){
			  //按钮【按钮二】的回调
			});
			console.log($row)
			

		})	

	}
	// events: function() {
	// 	let _self = this;
	// 	if(this.options.delbtn != '' || this.options.delbtn != false) {
			// this.$table.on('click', this.options.delbtn, function(e) {
			// 	e.preventDefault();
				// $.magnificPopup.open({
				// 	items: {
				// 		src: _self.options.deldialog.wrapper,
				// 		type: 'inline'
				// 	},
				// 	preloader: false,
				// 	modal: true,
				// 	callbacks: {
				// 		change: function() {
				// 			_self.dialog.$confirm.on( 'click', function( e ) {
				// 				e.preventDefault();

				// 				// _self.rowRemove( $row, postdata);
				// 				$.magnificPopup.close();
				// 			});
				// 		},
				// 		close: function() {
				// 			_self.dialog.$confirm.off( 'click' );
				// 		}
				// 	}
				// });
			// 	alert('刘丛梅')
			// })
	// 	}
	// 	if(this.options.editorbtn != '' || this.options.editorbtn != false) {
	// 		this.$table.on('click', this.options.editorbtn, function(e) {
	// 			e.preventDefault();
	// 			console.log($(this).closest( 'tr' ).index())
	// 			_self.rowEdit($(this).closest( 'tr' ))
	// 		})
	// 	}
	// 	return this;
	// },
	// rowEdit: function($row) {
	// 	let data = {};
	// 	let _self = this;
	// 	$row.children('td').each(function(i) {
	// 		var $this = $( this );
	// 		if($this.hasClass('actions') || $this.hasClass('sorting')) {

	// 		}else {
	// 			data[i] = $(this)[0].innerText
	// 		}
	// 	})
	// 	console.log(data);
	// 	$row.children('td').each(function(i, val) {
	// 		var $this = $( this );
	// 		if($this.hasClass('actions') || $this.hasClass('sorting')) {

	// 		}else {
	// 			$this.html( '<input type="text" class="form-control input-block" value="'+data[i]+'"/>' )
	// 		}
	// 		if($this.hasClass('actions')) {
	// 			_self.rowSetActionsEditing( $row );
	// 		}
	// 		console.log(val)
			
	// 		console.log($this)

		
	// 		// $this.html( '<input type="text" class="form-control input-block" value="'+html+'"/>' );
	// 	})
		
	// },

	// rowSetActionsEditing: function( $row ) {
	// 	$row.find( '.on-editing' ).removeClass( 'hidden' );
	// 	$row.find( '.on-default' ).addClass( 'hidden' );
	// },

	// rowSetActionsDefault: function( $row ) {
	// 	$row.find( '.on-editing' ).addClass( 'hidden' );
	// 	$row.find( '.on-default' ).removeClass( 'hidden' );
	// }

}


export {tableInit, TableAction, resData}